<template>
  <div class="app-container">
    <el-card header="出库单基本信息">
      <el-form label-width="108px" :model="form" ref="receiptForm" :rules="rules">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="出库单号" prop="billsId">
              <el-input v-model="form.billsId" placeholder="出库单号" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据日期" prop="checkDate">
              <el-date-picker
                v-model="form.checkDate"
                type="date"
                placeholder="选择单据日期"
                value-format="yyyy-MM-dd"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="创建人" prop="creatorName">
              <el-input v-model="form.creatorName" placeholder="创建人" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-input v-model="form.createTime" placeholder="创建时间" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="仓库" prop="stoId">
              <el-select filterable v-model="form.stoId" placeholder="请选择仓库" style="width: 100%">
                <el-option v-for="(item, index) in warehouseList" :key="index" :value="item.stoId"
                           :label="item.stoName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据状态" prop="billsStateName">
              <el-input v-model="form.billsStateName" placeholder="单据状态" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="出库类型" prop="billsType">
              <el-radio-group v-model="form.billsType" @change="generateOrderNo">
                <el-radio-button
                  v-for="item in wms_receipt_type"
                  :key="item.value"
                  :label="item.value"
                >{{ item.label }}
                </el-radio-button
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="往来单位" prop="billsCd">
              <el-select style="width: 100%" v-model="form.billsCd" placeholder="请选择往来单位" clearable filterable>
                <el-option v-for="item in merchantList" :key="item.id" :label="item.customerName"
                           :value="item.customerCode"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="总件数" prop="totalPackages">
              <el-input v-model="form.totalPackages" placeholder="总件数" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总数量" prop="totalQuantity">
              <el-input v-model="form.totalQuantity" placeholder="总数量" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks1">
              <el-input
                v-model="form.remarks1"
                placeholder="这里填写备注"
                rows="4"
                maxlength="100"
                type="textarea"
                show-word-limit="show-word-limit"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card header="商品明细" class="mt10">
      <el-button type="primary" size="default" @click="showAddItem">添加商品</el-button>
      <el-button type="success" size="default" @click="goToOut">提交</el-button>
      <el-table :data="detailList" border class="mt20">
        <el-table-column show-overflow-tooltip type="index" label="行号" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugId" label="商品编码" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugName" label="商品名称" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugBh" label="批准文号" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugGg" label="商品规格" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugDw" label="单位" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugNum" label="出库数量" align="center">
          <template #default="{row}">
            <el-input-number
              v-model="row.drugNum"
              :min="1"
              :max="row.availableStock || 9999"
              @change="handleStockChange(row)"
              placeholder="请输入出库数量"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="availableStock" label="可用库存" align="center">
          <template #default="{row}">
            <span :style="{color: row.availableStock <= 10 ? '#F56C6C' : '#67C23A'}">
              {{ row.availableStock || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="drugCd" label="生产厂家" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugBatchNo" label="批次号" align="center">
          <template #default="{row}">
            <el-input v-model="row.drugBatchNo" placeholder="批次号（可选）"></el-input>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="drugPd" label="生产日期" align="center">
          <template #default="{row}">
            <el-date-picker v-model="row.drugPd" type="date" placeholder="生产日期（可选）"
                            value-format="yyyy-MM-dd"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="drugExp" label="有效期" align="center">
          <template #default="{row}">
            <el-date-picker v-model="row.drugExp" type="date" placeholder="有效期（可选）"
                            value-format="yyyy-MM-dd"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <SkuSelect :show.sync="drawer" @getData="getList"/>
  </div>
</template>

<script>
import SkuSelect from './alterDocument.vue'
import {getAllWarehouseList} from "@/api/index/yxl";//获取仓库
import {
  queryAllList,//往来单位
  finishStoreOver,//完成出库
  finishStoreDetail,//获取单据详情
} from '@/api/storage/finishStore'

export default {
  name: 'outBills',
  components: {
    SkuSelect
  },
  data() {
    return {
      drawer: false,
      form: {
        billsId: '',//出库单号
        checkDate: '',//单据日期
        creatorName: '',//创建人
        createTime: '',//创建时间
        stoId: '',//仓库
        billsState: '0',//单据状态待拣货
        billsStateName: '待发货',//单据状态名称
        billsType: 'SalesWareHouseOut',//出库类型
        billsCd: '',//供应商
        remarks1: '',//备注
        totalPackages: 0,//总件数
        totalQuantity: 0,//总数量
      },
      wms_receipt_type: [
        {label: '销售出库', value: 'SalesWareHouseOut'},
        {label: '退货出库', value: 'ReturnWareHouseOut'},
        {label: '调拨出库', value: 'AllocateWareHouseOut'},
        {label: '返工出库', value: 'ReworkWareHouseOut'},
        {label: '销毁出库', value: 'DestoryWareHouseOut'},
        {label: '抽检出库', value: 'CheckWareHouseOut'},
        {label: '直调出库', value: 'DirectAllocateWareHouseOut'},
        {label: '赠品出库', value: 'GiftHouseOut'},
        {label: '其他出库', value: 'OtherHouseOut'},
        {label: '使用出库', value: 'RetailWareHouse0ut'}
      ],
      detailList: [],//table
      warehouseList: [],//仓库
      merchantList: [],//供应商
      rules: {
        checkDate: [
          {required: true, message: '请选择单据日期', trigger: 'change'},
        ],
        stoId: [
          {required: true, message: '请选择仓库', trigger: 'blur'},
        ],
        billsType: [
          {required: true, message: '请选择出库类型', trigger: 'blur'},
        ],
        billsCd: [
          {required: true, message: '请选择往来单位', trigger: 'blur'},
        ]
      }
    }
  },
  created() {
    this.getSelect();//获取仓库
    this.getCDs();//获取往来单位

    // 检查是否有billsId参数（编辑模式）
    if (this.$route.query.billsId) {
      this.loadBillsData(this.$route.query.billsId);
    } else {
      this.generateOrderNo();//生成单号
      this.initFormData();//初始化表单数据
    }
  },
  methods: {
    //初始化表单数据
    initFormData() {
      // 设置创建人（从store中获取当前登录用户名）
      this.form.creatorName = this.$store.getters.name || '系统管理员';

      // 设置创建时间和单据日期为当前时间
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      const currentDate = `${year}-${month}-${day}`;
      const currentDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      this.form.checkDate = currentDate;
      this.form.createTime = currentDateTime;
    },
    //获取往来单位
    getCDs() {
      queryAllList().then(res => {
        this.merchantList = res.data;
      })
    },
    //随机生成单号
    generateOrderNo() {
      const timestamp = new Date().getTime();
      const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');

      // 根据入库类型设置前缀
      let prefix = '';
      switch (this.form.billsType) {
        case 'SalesWareHouseOut': // 销售出库
          prefix = 'XC';
          break;
        case 'ReturnWareHouseOut': // 退货出库
          prefix = 'RC';
          break;
        case 'OtherHouseOut': // 其他出库
          prefix = 'QC';
          break;
        case 'AllocateWareHouseOut': // 调拨出库
          prefix = 'AC';
          break;
        case 'ReworkWareHouseOut': // 返工出库
          prefix = 'FC';
          break;
        case 'DestoryWareHouseOut': // 销毁出库
          prefix = 'HC';
          break;
        case 'CheckWareHouseOut': // 抽检出库
          prefix = 'CC';
          break;
        case 'DirectAllocateWareHouseOut': // 直调出库
          prefix = 'DC';
          break;
        case 'GiftHouseOut': // 赠品出库
          prefix = 'ZC';
          break;
        case 'RetailWareHouse0ut': // 使用出库
          prefix = 'SC';
          break;
        default:
          prefix = 'RK'; // 默认入库
      }
      this.form.billsId = `${prefix}${timestamp}${randomNum}`;
    },
    //完成出库操作
    goToOut() {
      // 先进行出库前验证
      if (!this.validateBeforeOut()) {
        return;
      }

      this.$confirm('确定完成出库吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.receiptForm.validate((valid) => {
          if (valid) {
            let data = {
              ...this.form,
              outDetailList: this.detailList
            }
            finishStoreOver(data).then(res => {
              this.$message.success(res.msg);
              this.$router.push({
                path: "/storage/finishStore",
              });
            }).catch(err => {
              this.$message.error('出库失败：' + (err.response?.data?.msg || err.message));
            })
          } else {
            return false
          }
        })
      }).catch(() => {
        this.$message.info('取消出库');
      });
    },
    //仓库下拉获取
    getSelect() {
      getAllWarehouseList().then(res => {
        this.warehouseList = res.data;
      })
    },
    //打开商品选中
    showAddItem() {
      this.drawer = true;
    },
    getList(selectedItems) {
      // 过滤掉已经存在的商品
      const newItems = selectedItems.filter(item =>
        !this.detailList.some(existing => existing.drugId === item.productCode)
      );

      // 将新商品添加到明细列表
      this.detailList = [
        ...this.detailList,
        ...newItems.map(item => {
          return {
            drugId: item.productCode,
            drugName: item.productName,
            drugGg: item.productSpec,
            drugBh: item.approvalNum || '', // 批准文号 (兼容旧字段)
            DrugPZWH: item.approvalNum || '', // 批准文号 (正确字段名，对应后端JsonProperty)
            drugBatchNo: '', // 批次号
            drugNum: 1, // 数量
            drugCd: item.manufacturer || '', // 生产厂家
            drugExp: '', // 有效期
            drugPd: '', // 生产日期
            drugDw: item.unitName, // 单位
            availableStock: item.stock || 0 // 可用库存，这里需要从后端获取真实库存数据
          };
        })
      ];

      if (newItems.length < selectedItems.length) {
        this.$message.warning('部分商品已存在，未重复添加');
      }

      // 计算总件数和总数量
      this.calculateTotals();

      // 检查库存充足性
      this.checkStockAvailability();
    },

    // 库存变化处理
    handleStockChange(row) {
      if (row.drugNum > row.availableStock) {
        this.$message.warning(`出库数量不能超过可用库存${row.availableStock}`);
        row.drugNum = row.availableStock;
      }
      this.calculateTotals();
    },

    // 检查库存充足性
    checkStockAvailability() {
      const lowStockItems = this.detailList.filter(item =>
        item.availableStock <= 10 && item.availableStock > 0
      );
      const outOfStockItems = this.detailList.filter(item =>
        item.availableStock <= 0
      );

      if (outOfStockItems.length > 0) {
        this.$message.error(`以下商品库存不足：${outOfStockItems.map(item => item.drugName).join('、')}`);
      } else if (lowStockItems.length > 0) {
        this.$message.warning(`以下商品库存较低：${lowStockItems.map(item => item.drugName).join('、')}`);
      }
    },

    //计算总件数和总数量
    calculateTotals() {
      let totalPackages = 0;
      let totalQuantity = 0;

      this.detailList.forEach(item => {
        // 总件数累加
        totalPackages += 1;

        // 总数量累加
        if (item.drugNum && !isNaN(item.drugNum)) {
          totalQuantity += parseFloat(item.drugNum);
        }
      });

      this.form.totalPackages = totalPackages;
      this.form.totalQuantity = totalQuantity;
    },
    //删除
    handleDelete(row) {
      const index = this.detailList.indexOf(row);
      if (index !== -1) {
        this.detailList.splice(index, 1);
        this.$message.success('删除成功');
        // 重新计算总件数和总数量
        this.calculateTotals();
      }
    },

    // 出库前的验证
    validateBeforeOut() {
      // 检查是否有商品明细
      if (this.detailList.length === 0) {
        this.$message.error('请添加出库商品明细');
        return false;
      }

      // 检查库存是否充足
      const insufficientItems = this.detailList.filter(item =>
        item.drugNum > item.availableStock
      );

      if (insufficientItems.length > 0) {
        this.$message.error(`以下商品库存不足，无法出库：${insufficientItems.map(item => item.drugName).join('、')}`);
        return false;
      }

      return true;
    },

    //加载出库单数据（编辑模式）
    loadBillsData(billsId) {
      finishStoreDetail(billsId).then(res => {
        if (res.code === 200 && res.data) {
          // 填充表单数据
          this.form = {
            billsId: res.data.billsId,
            checkDate: res.data.checkDate,
            creatorName: res.data.creatorName,
            createTime: res.data.createTime ? res.data.createTime.replace(/T/, ' ').substr(0, 19) : '',
            stoId: res.data.stoId,
            billsState: res.data.billsState,
            billsStateName: this.getBillsStateName(res.data.billsState),
            billsType: res.data.billsType,
            billsCd: res.data.billsCd,
            remarks1: res.data.remarks1,
            totalPackages: res.data.totalPackages || 0,
            totalQuantity: res.data.totalQuantity || 0,
          };

          // 填充明细数据，确保字段映射正确
          this.detailList = (res.data.outDetailList || []).map(item => ({
            drugId: item.drugId,
            drugName: item.drugName,
            drugGg: item.drugGg,
            drugBh: item.drugBh || item.approvalNum || '', // 批准文号，兼容不同字段名
            DrugPZWH: item.drugPzwh || item.DrugPZWH || item.drugBh || item.approvalNum || '', // 批准文号 (正确字段名)
            drugBatchNo: item.drugBatchNo || '', // 批次号
            drugNum: item.drugNum || 1, // 数量
            drugCd: item.drugCd || '', // 生产厂家
            drugExp: item.drugExp || '', // 有效期
            drugPd: item.drugPd || '', // 生产日期
            drugDw: item.drugDw || '', // 单位
            availableStock: item.availableStock || 0 // 可用库存
          }));

          // 重新计算总数（确保数据一致性）
          this.calculateTotals();
        }
      }).catch(error => {
        this.$message.error('加载数据失败：' + error.message);
        // 如果加载失败，回退到新增模式
        this.generateOrderNo();
        this.initFormData();
      });
    },

    //根据状态值获取状态名称
    getBillsStateName(state) {
      const stateMap = {
        '0': '已出库',
        '1': '未出库',
        '2': '已作废'
      };
      return stateMap[state] || '未知状态';
    }
  }
}
</script>

<style lang="scss" scoped>
.mt10 {
  margin-top: 10px;
}

.mt20 {
  margin-top: 20px;
}

.w200 {
  width: 200px;
}

.el-table {
  .el-input-number {
    width: 120px;
  }

  .el-date-editor {
    width: 150px;
  }
}
</style>
